/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.model;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.client.ui.HasName;
import za.org.foobar.famon.util.DB;
import za.org.foobar.famon.util.DBQuery;

import javax.jdo.annotations.*;
import java.util.List;

/**
 *
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class ApplicationInstance extends ModelObject implements HasName {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;

    @Persistent
    private Application application;

    @Persistent
    private String name;

    public ApplicationInstance() {
    }

    public ApplicationInstance(String name) {
        this.name = name;
    }

    public Key getId() {
        return id;
    }

    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DBQuery<Failure> getFailureListQuery(boolean orderBy) {
        DBQuery<Failure> q = DB.createDBQuery(Failure.class)
                .addWhere("applicationInstanceId == applicationInstanceIdParam")
                .addParameter("applicationInstanceIdParam", id);
        if (orderBy) {
            q.addOrderBy("date desc");
        }
        return q;
    }
    public List<Failure> getFailureList() {
        return getFailureListQuery(true).getResultList();
    }

    public void delete() {
        //Delete all failures
        deleteAll(getFailureList());
//        getFailureListQuery(false).deletePersistentAll(id);
        //Delete self
        super.delete();
    }
}
